<?php

namespace App\Composers;

use Illuminate\View\View;
//use Illuminate\Support\Facades\Redis;
use App\Repositories\Eloquent\RoleRepository as Role;
use App\Repositories\Eloquent\PermissionRepository as Permission;

class MenuComposer
{
    private $title;
    protected $navbar;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->title = 'messages.'.\Route::currentRouteName();

        $this->setMenus();
    }


    public function getMenus()
    {
        return $this->navbar;
    }


    public function compose(View $view)
    {
        $view->with([
            'navbar' => $this->getMenus(),
            'title' => $this->title,
        ]);
    }


    protected function setMenus()
    {
        $staff = \Auth::guard('admin')->user();

        //管理员
        if( $staff->supervisor() ) {

            /*$rows = unserialize(Redis::get(CACHE_PERMISSION_P));

            if (!$rows) {
                $rows = \App\Models\Acl\Permission::where('status', STATUS_NORMAL)
                    ->orderBy('order', 'ASC')
                    ->get();

                Redis::set(CACHE_PERMISSION_P, serialize($rows));
            }*/
            if (\Cache::has(CACHE_PERMISSION_P))
            {
                $rows = \Cache::get(CACHE_PERMISSION_P);
            }
            else
            {
                $rows = \App\Models\Acl\Permission::where('status', STATUS_NORMAL)
                    ->orderBy('order', 'ASC')
                    ->get();

                \Cache::put(CACHE_PERMISSION_P, $rows);
            }

        }
        //非管理员
        else {
            $rows = \Cache::get(CACHE_PERMISSION_N.'.'.$staff->id);

            if (!$rows){
                //登录用户所拥有的权限
                $permissions = $staff->getAllPermissions()->where('status', STATUS_NORMAL);

                //拥有的权限所属父级菜单ID
                $pluck = $staff->getAllPermissions()->pluck('parent')->unique()->values()->all();

                //父级菜单集合
                $parent = \App\Models\Acl\Permission::whereIn('id', $pluck)->get();

                //父级与所属权限合并
                $rows = $permissions->merge($parent)->sortBy('order');

                \Cache::put(CACHE_PERMISSION_N.'.'.$staff->id, $rows);
            }

        }

        $this->navbar = self::getChildMenu($rows, 0);
    }


    public static function getChildMenu($data, $pid)
    {
        $tree = array();

        foreach($data as $key => $value)
        {
            if($value['parent'] == $pid)
            {
                $value['child'] = self::getChildMenu($data, $value['id']);

                $tree[] = $value;
            }
        }
        return $tree;
    }







}